<template>
	
	<view class="list" style="display: flex;flex-direction: column;align-items: center;">
		<view class="top-tab">
			<view class="top-tab-cell" :class="{active: isPay == 1 }" @click="changeStatus(1)">全部</view>
			<view class="top-tab-cell" :class="{active: isPay == 0 }" @click="changeStatus(0)">待支付</view>
		</view>
		<template v-for="(item,index) in myrecipeDataList">
			<view class="chufang-card" :key="item.id" @click="tochufangxq(index)">
				<view class="chufang-card-row" style="
					display: flex;align-items: center;justify-content: space-between;">
					<view>
						<text style="color: #00BAAD;margin-right: 10rpx;">【诊断】</text>
						<text v-for="(diseaItem,diseaIdx) in item.diseaInfo" :key="diseaIdx">{{diseaItem.name}}</text>
					</view>
					
					<view style="color: #c1381c;">
						{{item.payState == 0?'未支付':item.payState== 1?'已支付':item.payState== 2?'已派药':item.payState== 3?'待退款':item.payState== 4?'已退费':item.payState== 5?'异常支付':item.payState== 7?'拒绝退费':item.payState== 9?'支付超时':item.payState == 10?'处方流转授权':item.payState== 11?'处方待流转':item.payState== 12?'处方流转成功':'处方流转失败'}}
					</view>
				</view>
				<view class="chufang-card-row">
					<text style="margin-right: 10rpx;">处方号：</text>
					<text>{{item.recipeCode}}</text>
				</view>
				<view class="chufang-card-row">
					<text style="margin-right: 10rpx;">医生：</text>
					<text>{{item.doctorName}}</text>
				</view>
				<view class="chufang-card-row">
					<text style="margin-right: 10rpx;">RP:</text>
					<template v-if="item.payState == 1 || item.payState == 2">
						<text v-for="(recipeItem,recipeIdx) in item.doctorNormalRecipeDrug" :key="recipeIdx">
							{{recipeItem.drugName+recipeItem.drugSpecificationName}}
						</text>
					</template>
					<template>
						<text style="color: #c1381c;" v-if="item.payState == 0">
							支付后可见
						</text>
					</template>
				</view>
				<view class="chufang-card-row">
					<text style="margin-right: 10rpx;">时间：</text>
					<text>{{changeDateFormat(item.sendDate)}}</text>
				</view>
				<view class="chufang-btn" v-if="item.payState== 1">
					<view style="border: 2rpx solid #84DDD7;width: 150rpx;height: 50rpx;line-height:50rpx;border-radius: 25rpx;text-align: center;color: #00BAAD;" @click.stop="regulatorRefundReport(index)">撤销结算</view>
				</view>
			</view>
		</template>
		<!-- <view v-for="(item,index) in myrecipeDataList" :key="item.id">
			<view class="mt15 pl25 pr25 bgfff">
				<view class="pt30 pb30 flex flex-ac bb">
					<image class="haed mr25" :src="item.doctorPhoto"></image>
					<text class="bold mr25">诊断医生：{{item.doctorName}}</text>
					<text class="it1 ft12 c666 ftr">就诊人：{{item.treatName}}</text>
				</view>
				<view class="c666 pt25 pb25  bb">
					<text class="twoLine" v-if="item.problem=='无'">病情描述：复购处方</text>
					<text class="twoLine" v-if="item.problem!='无'">病情描述：{{item.problem}}</text>
				</view>
				<view class="pt25 pb25 bb">
					<text>诊断结果：</text>
					<text class="c666 ml10">{{changeDiseaInfoName(item.diseaInfo)}}</text>
				</view>
				<view class="pt25 pb25 flex flex-ac flex-pj">
					<text class="ft12 c666 it1">{{changeDateFormat(item.treatDate)}}</text>
					<text v-if="item.problem!='无'" class="nbtn" :id="item.recipeId" @click="saveRecipe">复购药品</text>
					<navigator :url="'/pages3/prescriptiondetail/index?recipeId='+ item.recipeId">
						<text class="nbtn ml15">查看处方</text>
					</navigator>
				</view>
			</view>
		</view> -->
		<view class="win flex flex-ac flex-pc" v-if="winstate">
			<view class="wincon bgfff flex flex-ac flex-pc">
			   <image class="ques mr30" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/ques2.png"></image>
				<view class="ftc pl10 box">
					<view class="cfff bold ft16">已发送药房审核</view>
					<view class="cfff mt15 ft12">请注意查收消息！</view>
				</view>
			</view>
		</view>
		<uni-load-more :status="message" :contentText="contentText" @clickLoadMore="loadMore"  ></uni-load-more>
		<uni-popup ref="popup" type="message">
		    <uni-popup-message :type="warnType" :message=warnMessage :duration="warnTime"></uni-popup-message>
		</uni-popup>
		<view style="text-align: center;font-size: 10px;" v-if="statusOne">由重庆拓诊信息技术有限公司提供技术支持</view>
	</view>
</template>

<script>
const WxAuth =  require('@/utils/wxlogin');
export default {
	data() {
		return {
			statusOne:false,
			warnMessage:'错误',//消息内容
			warnType:'warn',//消息类型  success/warn/info/error
			warnTime:1000,//消息提醒延长时间
			hasNextPage:true,//是否有下一页
			message:'noMore',
			contentText: {contentdown: "点击显示更多",contentrefresh: "正在加载...",contentnomore: "没有更多数据了"},
			pageIndex:1,
			winstate:false,
			myrecipeDataList:[],//获取用户处方列表
			usrUserId:null,
			myrecipeDataLists:[],
			isPay: 0,// 我的处方未支付-0，其他状态-1
		};
	},
	onLoad(option) {
		//初始化数据
		this.usrUserId=uni.getStorageSync("usrUserId")
		this.isPay = option.recipeNum == 0?1:0
		// this.usrUserId = 5557
	},
	onShow() {
		this.initData(this.pageIndex);
	},
	onReachBottom(){
		this.statusOne=true
	},
	methods: {
		changeStatus(val){
			this.isPay = val
			this.pageIndex = 1
			this.initData(this.pageIndex);
		},
		regulatorRefundReport(val){
			uni.navigateTo({
			    url: '/pages3/cxchuf/index?medicalNum='+this.myrecipeDataList[val].medDocOrdsId
			});
		},
		tochufangxq(val){
			// recipeId
			// console.log(val)
			uni.navigateTo({
			    url: '/pages3/prescriptiondetail/index?recipeId='+this.myrecipeDataList[val].recipeId
			});
		},
		//加载更多
		loadMore(e){
			if(e.detail.status =='more'){
				var that = this;
				that.message = 'loading';
				that.pageIndex = that.pageIndex+1;
				setTimeout(()=>{
					that.initData(that.pageIndex)
					if(that.hasNextPage){
						that.message = 'more';
					}else{
						that.message = 'noMore';
					}
				},500);
			}
		},
		showwinstate(e){
			// this.winstate = true;
			// setTimeout(()=>{
			// 	this.winstate = false;
			// },2000)
			//先判断当前处方是否支付状态是否已经结束
			var that = this;
			var recipeId = e.target.id;
			uni.showModal({
			    title: '提示',
			    content: '是否确定复购药品',
			    success: function (res) {
			        if (res.confirm) {
						WxAuth.onLogin().then(code => {
							var parm = {};
							parm.recipeId = recipeId;
							parm.thirdPayEnum = 'weixinApplet';
							parm.code = code;//code值(5分钟失效)
							this.func.$request('recipe/repurchasePay.tz',parm,'POST','application/x-www-form-urlencoded').then(item=>{
								if(item.data.success){
									var timestamp = item.data.result.timeStamp;
									var nonceStr = item.data.result.nonceStr;
									var packages = 'prepay_id='+item.data.result.prepayid;
									var paySign = item.data.result.sign;
									uni.requestPayment({
									    timeStamp: timestamp,
									    nonceStr: nonceStr,
									    package: packages,
									    signType: 'MD5',
									    paySign: paySign,
									    success: function (res) {
											//that.saveRecipe(recipeId);
									        that.warnMessage = '支付成功';
									        that.warnType = 'success';
									        that.$refs.popup.open();
									    },
									    fail: function (err) {
									        
									    }
									});
								}else{
									that.warnMessage = item.data.errMsg;
									that.warnTime  = 3000;
									that.$refs.popup.open();
								}
							}).catch(error=>{
								that.warnMessage = '支付失败';
								that.warnType = 'error';
								that.$refs.popup.open();
							})
				
						 });
			        } else if (res.cancel) {
			            
			        }
			    }
			});
			
		},
		//复购生成处方
		saveRecipe(e){
			var that=this;
			var recipeId = e.target.id;
			this.func.$request('wx/sendRepRecipeById.tz',{recipeId : recipeId,usrUserId:that.usrUserId},'GET').then(res=>{
				if(res.data.success){
					that.initData(1);
					uni.showToast({
						title:"已发送药房审核,请注意消息"
					})
				}else{
					that.message = 'noMore';
				}
			}).catch(error=>{
				that.message = 'noMore';
			})
		},
		initData(pageIndex){
			var that = this;
			var usrUserId = that.usrUserId;//用户id
			let openid=uni.getStorageSync('openId')
			var hosId = this.hspId;//永川医院id
			if(pageIndex == 1){
				that.myrecipeDataList = []
			}
			let data={usrUserId : usrUserId, hosId : hosId,current:pageIndex,wxType:'1'}
			this.func.$request('repRecipe/getRecipieList.tz',data,'GET').then(res=>{
				if(res.data.success){
					var size = res.data.result.length;
					if(size==10){
						that.hasNextPage=true;
						that.message = 'more';
					}else{
						that.hasNextPage=false;
						that.message = 'noMore';
					}
					//that.myrecipeDataList =  res.data.result;
					if(res.data.result.length>0){
						res.data.result.forEach(function(item,index){
							that.myrecipeDataList.push(item);
						});
					}
					var uniques = [];
					var stringify = {};
					for (var i = 0; i < that.myrecipeDataList.length; i++) {
					    var keys = Object.keys(that.myrecipeDataList[i]);
					    keys.sort(function(a, b) {
					        return (Number(a) - Number(b));
					    });
					    var str = '';
					    for (var j = 0; j < keys.length; j++) {
					        str += JSON.stringify(keys[j]);
					        str += JSON.stringify(that.myrecipeDataList[i][keys[j]]);
					    }
					    if (!stringify.hasOwnProperty(str)) {
					        uniques.push(that.myrecipeDataList[i]);
					        stringify[str] = true;
					    }
					}
					that.myrecipeDataLists=uniques
					
				}
			}).catch(error=>{
				that.message = 'noMore';
			})
		},
		//格式化时间
		changeDateFormat(cellval) {
		　　　　var dateVal = cellval + "";
		　　　　if (cellval != null) {
		　　　　　　var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
		　　　　　　var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
		　　　　　　var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		　　　　　　var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		　　　　　　var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		　　　　　　var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		　　　　　　return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
		　　　　}
		
		　},
		changeDiseaInfoName(obj){
			if(obj.length>0){
				var arr = [];
				obj.forEach(function(item,index){
					arr.push(item.name)
				});
				return arr.join(",");
			}else{
				return '';
			}
		}
	}
};
</script>

<style lang="less">
	.top-tab{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #FFFFFF;
		position: fixed;
		top:0rpx;
		left: 0rpx;
		z-index: 999;
		.top-tab-cell{
			width: 50%;
			text-align: center;
			height: 100rpx;
			line-height: 100rpx;
			box-sizing: border-box;
		}
		.active{
			color: #BE965B;
			border-bottom: 2rpx solid #BE965B;
		}
	}
	.chufang-card{
		border-top: 1rpx solid #efefef;
		border: 1px solid #F2F9F9;
		box-shadow: 0px 1px 17px 1px rgba(162, 215, 211, 0.16);
		border-radius: 32rpx;
		background-color: #FFFFFF;
		margin-top: 20rpx;
		padding-left: 40rpx;
		padding-top: 20rpx;
		width: calc( 100vw - 40rpx );
		box-sizing: border-box;
		// margin-left: 30rpx;
		.chufang-card-row{
			width: calc( 100% - 40rpx );
			word-break:break-all;
			text-align: left;
			margin-bottom: 20rpx;
		}
		.chufang-btn{
			width: calc(100% - 40rpx);
			border-top: 5rpx solid #E6EAEA;
			padding-top: 20rpx;
			padding-bottom: 20rpx;
			margin-top: 20rpx;
			display: flex;
			justify-content: flex-end;
		}
	}
	
	
	.win{
		position: fixed;
		width: 100%;
		height: 100vh;
		left: 0;
		top: 0;
		
		.wincon{
			width: 480rpx;
			height: 225rpx;
			background: rgba(0,0,0,0.8);
			
			.ques{
				width: 63rpx;
				height: 63rpx;
			}
		}
	}
page {
	background: #efefef;
}
.list {
	padding-top: 100rpx;
	.text {
		line-height: 45rpx;
	}

	.haed {
		width: 65rpx;
		height: 65rpx;
		border-radius: 50%;
	}

	.now {
		display: inline-block;
		width: 245rpx;
		line-height: 50rpx;
		border-radius: 10rpx;
		border: 1rpx solid #efefef;
		text-align: center;
	}
	.nbtn {
		display: inline-block;
		line-height: 50rpx;
		padding: 0 20rpx;
		border-radius: 10rpx;
		border: 1rpx solid #efefef;
	}
}
</style>
